package com.guojian.jdbc.mapper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.LinkedCaseInsensitiveMap;

import com.alibaba.fastjson.JSON;
import com.google.common.base.CaseFormat;
import com.google.common.collect.Maps;
import com.guojian.common.utils.StringUtilsx;

public class StringMapRowMapper implements RowMapper<Map<String, String>> {

	/**
	 * 是否增加驼峰似的名字USER_ID->userId
	 */
	private boolean isAddLowerCaseOfName = false;

	public StringMapRowMapper() {
	}

	public StringMapRowMapper(boolean isAddLowerCaseOfName) {
		this.isAddLowerCaseOfName = isAddLowerCaseOfName;
	}

	@Override
	public Map<String, String> mapRow(ResultSet rs, int rowNum) throws SQLException {
		ResultSetMetaData rsmd = rs.getMetaData();
		int columnCount = rsmd.getColumnCount();
		Map<String, String> mapOfColValues = createColumnMap(columnCount);
		for (int i = 1; i <= columnCount; i++) {
			String columnName = JdbcUtils.lookupColumnName(rsmd, i);
			String columnValue = getColumnValue(rs, i);
			mapOfColValues.put(columnName, columnValue);
			if (isAddLowerCaseOfName) {
				mapOfColValues.putIfAbsent(StringUtilsx.toLowerCaseOfCamel(columnName), columnValue);
			}
		}
		return mapOfColValues;
	}

	protected Map<String, String> createColumnMap(int columnCount) {
		if (isAddLowerCaseOfName) {
			return Maps.newLinkedHashMap();
		}
		return new LinkedCaseInsensitiveMap<String>(columnCount);//不区分大小写,小写会把大写的变量名覆盖
	}

	protected String getColumnValue(ResultSet rs, int index) throws SQLException {
		return ObjectUtils.toString(JdbcUtils.getResultSetValue(rs, index)).trim();
	}

	public static void main(String[] args) {
		System.out.println(StringUtils.toRootLowerCase("Abc_EFD_e"));// abc_efd_e
		System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "TESTDATA"));// testdata
		System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "TEST_DATA"));// testData
		System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "test_data"));// testData
		System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "test_Data"));// testData

		Map<String, Object> maps = new LinkedCaseInsensitiveMap<>();
		maps.put("guojian", "guojian");
		System.out.println(JSON.toJSONString(maps));

	}

}
